package fzdy.tools;

import com.alibaba.fastjson.JSONObject;
import fzdy.struct.SmsType;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

@Component("smssender")
public class SmsSender {
    @Value("${appId}")
    private String APP_ID;//应用ID------登录平台在应用设置可以找到
    @Value("${appSecret}")
    private String APP_SECRET;//应用secret-----登录平台在应用设置可以找到
    @Value("${accessToken}")
    private String ACCESS_TOKEN;//访问令牌AT-------CC模式，AC模式都可，推荐CC模式获取令牌
    @Value("${postUrl}")
    private String postUrl;

    @Async
    public void sendSms(SmsType type, String tel, String content){


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("acceptor_tel",tel);
        jsonObject.put("template_id",type.toString());
        jsonObject.put("template_param",content);
        jsonObject.put("app_id",APP_ID);
        jsonObject.put("access_token",ACCESS_TOKEN);
        jsonObject.put("timestamp",DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));


        HttpTool.sendReqMsg(formatJson(jsonObject),postUrl);

        return;

    }

    private String formatJson(JSONObject jsonObject) {
        StringBuilder stringBuilder = new StringBuilder();
        jsonObject.forEach((key, value) -> {
            stringBuilder.append(key);
            stringBuilder.append("=");
            stringBuilder.append(value);
            stringBuilder.append("&");
        });
        return stringBuilder.toString().substring(0,stringBuilder.toString().length()-1);
    }
}
